﻿using BusinessEntity;
using BusinessRepository;
using learun.util;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{
   public class LogRule
    {

        #region 获取数据
        /// <summary>
        /// 日志列表
        /// </summary>
        /// <param name="pagination">分页</param>
        /// <param name="queryJson">查询参数</param>
        /// <param name="userId">操作用户Id</param>
        /// <returns></returns>
        public Task<IEnumerable<LogEntity>> GetPageList(Pagination pagination, string queryJson, string userId)
        {
            var strSql = new StringBuilder();
            strSql.Append("SELECT * FROM LogEntity t WHERE 1=1");
            var queryParam = queryJson.ToJObject();

            int categoryId = 0;
            DateTime startTime = DateTime.Now;
            DateTime endTime = DateTime.Now;
            string operateUserId = null;
            string operateAccount = null;
            string operateType = null;
            string module = null;
            string keyword = null;
            // 日志分类
            if (!queryParam["CategoryId"].IsEmpty())
            {
                categoryId = queryParam["CategoryId"].ToInt();
                strSql.Append(" AND F_CategoryId = @categoryId ");
            }
            // 操作时间
            if (!queryParam["StartTime"].IsEmpty() && !queryParam["EndTime"].IsEmpty())
            {
                startTime = queryParam["StartTime"].ToDate();
                endTime = queryParam["EndTime"].ToDate();
                strSql.Append(" AND( F_OperateTime >= @startTime AND F_OperateTime <= @endTime )");
            }
            // 操作用户Id
            if (!queryParam["OperateUserId"].IsEmpty())
            {
                operateUserId = queryParam["OperateUserId"].ToString();
                strSql.Append(" AND F_OperateUserId = @operateUserId ");
            }
            // 操作用户账户
            if (!queryParam["OperateAccount"].IsEmpty())
            {
                operateAccount = "%" + queryParam["OperateAccount"].ToString() + "%";
                strSql.Append(" AND F_OperateAccount like @operateAccount ");
            }
            // 操作类型
            if (!queryParam["OperateType"].IsEmpty())
            {
                operateType = queryParam["OperateType"].ToString();
                strSql.Append(" AND F_OperateType = @operateType ");
            }
            // 功能模块
            if (!queryParam["Module"].IsEmpty())
            {
                module = queryParam["Module"].ToString();
                strSql.Append(" AND F_Module = @module ");
            }
            // 登录用户id
            if (!string.IsNullOrEmpty(userId))
            {
                strSql.Append(" AND F_OperateUserId = @userId ");
            }
            // 关键字
            if (!queryParam["keyword"].IsEmpty())
            {
                keyword = "%" + queryParam["keyword"] + "%";
                strSql.Append(" AND (F_Module like @keyword || F_OperateType like @keyword || F_IPAddress like @keyword   )");
            }
            return new RepositoryFactory().BaseRepository().FindList<LogEntity>(strSql.ToString(), new { categoryId, startTime, endTime, operateUserId, operateAccount, operateType, module, userId, keyword }, pagination);
        }


        /// <summary>
        /// 日志实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public Task<LogEntity> GetEntity(string keyValue)
        {
            return new RepositoryFactory().BaseRepository().FindEntity<LogEntity>(keyValue);
        }
        #endregion

        #region 写日志
        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="categoryId">日志分类Id</param>
        /// <param name="keepTime">保留时间段内</param>
        public async Task Remove(int categoryId, string keepTime)
        {
            DateTime operateTime = DateTime.Now;
            if (keepTime == "7")//保留近一周
            {
                operateTime = DateTime.Now.AddDays(-7);
            }
            else if (keepTime == "1")//保留近一个月
            {
                operateTime = DateTime.Now.AddMonths(-1);
            }
            else if (keepTime == "3")//保留近三个月
            {
                operateTime = DateTime.Now.AddMonths(-3);
            }

            await new RepositoryFactory().BaseRepository().ExecuteSql("  Delete  From LogEntity where F_CategoryId = @categoryId AND F_OperateTime <= @operateTime ", new { categoryId, operateTime });
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="logEntity">对象</param>
        public static async Task Write(LogEntity logEntity)
        {
            logEntity.F_LogId = Guid.NewGuid().ToString();
            logEntity.F_OperateTime = DateTime.Now;
            logEntity.F_DeleteMark = 0;
            logEntity.F_EnabledMark = 1;

            await new RepositoryFactory().BaseRepository().Insert(logEntity);
        }

        
        #endregion

        public static string ExceptionFormat(Exception ex)
        {
            StringBuilder strInfo = new StringBuilder();
            strInfo.Append("1. 异常: " + ex.Message + "\r\n");
            strInfo.Append("2. 来源: " + ex.Source + "\r\n");
            strInfo.Append("3. 实例: " + ex.StackTrace + "\r\n");
            return strInfo.ToString();
        }
    }
}
